function loadStudentData() {
    // 调用 API 获取学生数据
    $.ajax({
        url: "http://localhost:8080/people/list",
        method: "GET",
        dataType: "json",
        contentType: "application/json",
        cache: false,
        success: function (response) {
            // 清空学生表格数据
            $("#students-tbody").empty();

            // 遍历后端返回的学生数组
            $.each(response.data, function (index,student) {
                // 生成表格行 HTML
                let studentRowHTML = `<tr>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.sex}</td>
                    <td>${student.age}</td>
                    <td>${student.major}</td>
                    <td>${student.code}</td>
                    <td>${student.address}</td>
                    <td>${student.status}</td>
                    <td>
                    <button class="btn btn-sm btn-primary">编辑</button>
                    <button class="btn btn-sm btn-danger" data-student-id="${student.id}">删除</button>
                    </td>
                    </tr>`;

                // 将表格行添加到表格中
                $("#students-tbody").append(studentRowHTML);
            });
        },
        error: function (error) {
            // 如果出现错误，弹出错误消息
            console.error("获取学生数据失败：", error);
        }
    });
}

/**
 * 增加学生
 */
function initializeStudentTable() {
    loadStudentData();

    //清理学生框
    function resetForm() {
        $("#student-name").val("");
        $("#student-sex").val("");
        $("#student-age").val("");
        $("#student-major").val("");
        $("#student-code").val("");
        $("#student-address").val("");
        $("#student-status").val("");
    }

    $("#add-student-btn").click(function () {
        console.log("添加学生按钮被点击"); //
        var student_name = $("#student-name").val();
        var student_sex = $("#student-sex").val();
        var student_age = $("#student-age").val();
        var student_major = $("#student-major").val();
        var student_code = $("#student-code").val();
        var student_address = $("#student-address").val();
        var student_status = $("#student-status").val();
        if (student_address === "" || student_name == "" || student_sex == "" || student_age == "" || student_major == "" || student_code == "") {
            alert("输入不能为空！");
            return;
        }
        $.ajax({
            url: "http://localhost:8080/people/add",
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            cache: false,
            data: JSON.stringify({
                "name": student_name,
                "sex": student_sex,
                "age": student_age,
                "major": student_major,
                "code": student_code,
                "address": student_address,
                "status": student_status
            }),
            success: function (response) {
                // 登录成功，可以执行一些操作，例如跳转到主页
                if (response.message == "ok") {
                    alert("添加成功！");
                    resetForm();
                    loadStudentData();
                } else {
                    // 如果登录失败，显示提示信息
                    alert(response.message);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                // 发生错误时的处理
                alert("登录处理过程中发生问题！");
            }
        })

    });
    /**
     * 删除学生
     */
    // ... 原有的删除学生事件处理代码
    $("#students-tbody").on("click", ".btn-danger", function () {
        console.log("删除学生按钮被点击");
        let studentId = $(this).data("student-id");
        // 确认是否要删除
        if (!confirm("确定要删除此学生吗？")) {
            return;
        }

        // 调用后端API以删除学生
        $.ajax({
            url: `http://localhost:8080/people/delete/${studentId}`, // 根据实际API接口进行修改
            method: "DELETE",
            dataType: "json",
            contentType: "application/json",
            cache: false,
            success: function (response) {
                if (response.message == "ok") {
                    alert("学生已删除！");
                    // 重新加载学生数据
                    loadStudentData();
                } else {
                    alert("删除失败: " + response.message);
                }
            },
            error: function (error) {
                console.error("删除学生失败：", error);
            }
        });
    });
    /**
     * 查询
     */
    $('#search-student-btn').on('click', async function () {

        // 获取查询的学生 ID
        const studentId = $('#search-student-input').val();

        // 根据查询的学生 ID 调用您的后端 API
        const response = await fetch(`http://localhost:8080/people/select/${studentId}`);
        // 处理响应结果
        if (response.ok) {
            const responseData = await response.json();
            const data = responseData.data;
            let avatarURL = data.avatar ? '.' + data.avatar : './avatars/default_avatar.png';
            // 创建表格行HTML并使用响应数据填充
            let searchResultHtml = `
    <tr>
      <td><img src="${avatarURL}" width="50" height="50"></td>
      <td>${data.name}</td>
      <td>${data.sex}</td>
      <td>${data.age}</td>
      <td>${data.major}</td>
      <td>${data.code}</td>
      <td>${data.address}</td>
      <td>${data.status}</td>
    </tr>
    `;

            // 将结果数据插入表格行
            $('#searchResult').html(searchResultHtml);

            // 使用 Bootstrap 4.x 显示模态框
            $('#studentSearchResultModal').modal('show');
        } else {
            alert(`查询失败：${response.statusText}`);
        }
        // 在查询完成后清空查询输入框
        $('#search-student-input').val('');
    });


    /**
     * 编辑学生
     */
    $("#students-tbody").on("click", ".btn-primary", function () {
        // 获取当前行的学生数据
        let studentRow = $(this).parent().parent();
        let studentId = studentRow.children().eq(0).text();
        let studentName = studentRow.children().eq(1).text();
        let studentSex = studentRow.children().eq(2).text();
        let studentAge = studentRow.children().eq(3).text();
        let studentMajor = studentRow.children().eq(4).text();
        let studentCode = studentRow.children().eq(5).text();
        let studentAddress = studentRow.children().eq(6).text();
        let studentStatus = studentRow.children().eq(7).text();
        // 在模态框中设置学生数据
        $('#edit-student-id').val(studentId);
        $('#edit-student-name').val(studentName);
        $('#edit-student-sex').val(studentSex);
        $('#edit-student-age').val(studentAge);
        $('#edit-student-major').val(studentMajor);
        $('#edit-student-code').val(studentCode);
        $('#edit-student-address').val(studentAddress);
        $('#edit-student-status').val(studentStatus);

        // 显示模态框
        $('#editStudentModal').modal('show');
    });

// 点击“保存更改”按钮时更新学生数据
    $('#saveChangesBtn').click(function () {
        let studentId = $('#edit-student-id').val();
        let studentName = $('#edit-student-name').val();
        let studentSex = $('#edit-student-sex').val();
        let studentAge = $('#edit-student-age').val();
        let studentMajor = $('#edit-student-major').val();
        let studentCode = $('#edit-student-code').val();
        let studentAddress = $('#edit-student-address').val();
        let studentStatus = $('#edit-student-status').val();

        // 发送更新请求给后端 API
        updateStudentData(studentId, studentName, studentSex, studentAge, studentMajor, studentCode, studentAddress, studentStatus);

        // 隐藏模态框
        $('#editStudentModal').modal('hide');
    });
}
    /**
     * 编辑功能的函数
     * @param studentId
     * @param studentName
     * @param studentSex
     * @param studentAge
     * @param studentMajor
     * @param studentCode
     * @param studentAddress
     * @param studentStatus
     */
    function updateStudentData(studentId, studentName, studentSex, studentAge, studentMajor, studentCode, studentAddress, studentStatus) {
        // 通过 AJAX 向后端发送更新请求
        $.ajax({
            url: `http://localhost:8080/people/edit/${studentId}`,
            method: "PUT",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "name": studentName,
                "sex": studentSex,
                "age": studentAge,
                "major": studentMajor,
                "code": studentCode,
                "address": studentAddress,
                "status": studentStatus
            }),
            cache: false,
            success: function(response) {
                alert("更改成功！");
                // 请求成功，重新加载学生数据
                loadStudentData();
            },
            error: function(error) {
                // 如果出现错误，弹出错误消息
                console.error("更新学生数据失败：", error);
            }
        });
    }

function bindStudentTableEvents() {
    initializeStudentTable();
}



